<template>
  <div class="dashboard-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-left">
        <h1 class="logo">校园智慧竞赛平台 - 管理后台</h1>
      </div>
      <div class="header-right">
        <span class="admin-name">{{ adminName }}</span>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </header>

    <div class="main-content">
      <!-- 侧边栏 -->
      <aside class="sidebar">
        <nav class="nav-menu">
          <div class="menu-item" :class="{ active: currentRoute === 'dashboard' }" @click="navigateTo('/dashboard')">
            <i class="icon">📊</i>
            <span>仪表盘</span>
          </div>
          <div class="menu-item" :class="{ active: currentRoute === 'user-audit' }" @click="navigateTo('/user-audit')">
            <i class="icon">👥</i>
            <span>用户审核</span>
          </div>
          <div class="menu-item" :class="{ active: currentRoute === 'user-management' }" @click="navigateTo('/user-management')">
            <i class="icon">👤</i>
            <span>用户管理</span>
          </div>
          <div class="menu-item" :class="{ active: currentRoute === 'team-management' }" @click="navigateTo('/team-management')">
            <i class="icon">⚡</i>
            <span>队伍管理</span>
          </div>
          <div class="menu-item" :class="{ active: currentRoute === 'homepage-editor' }" @click="navigateTo('/homepage-editor')">
            <i class="icon">🏠</i>
            <span>主页编辑</span>
          </div>
          <div class="menu-item" :class="{ active: currentRoute === 'system-notifications' }" @click="navigateTo('/system-notifications')">
            <i class="icon">📢</i>
            <span>通知管理</span>
          </div>
          <div class="menu-item" :class="{ active: currentRoute === 'news-management' }" @click="navigateTo('/news-management')">
            <i class="icon">📰</i>
            <span>新闻管理</span>
          </div>
          <div class="menu-item" :class="{ active: currentRoute === 'event-management' }" @click="navigateTo('/event-management')">
            <i class="icon">🏆</i>
            <span>赛事管理</span>
          </div>
        </nav>
      </aside>

      <!-- 主要内容区域 -->
      <main class="content">
        <div class="dashboard-overview">
          <h2>系统概览</h2>
          
          <!-- 统计卡片 -->
          <div class="stats-grid">
            <div class="stat-card">
              <div class="stat-icon">👨‍🎓</div>
              <div class="stat-info">
                <h3>学生用户</h3>
                <p class="stat-number">{{ statistics.totalStudents || 0 }}</p>
                <p class="stat-change">待审核: {{ statistics.pendingStudents || 0 }}</p>
              </div>
            </div>
            
            <div class="stat-card">
              <div class="stat-icon">👨‍🏫</div>
              <div class="stat-info">
                <h3>教师用户</h3>
                <p class="stat-number">{{ statistics.totalTeachers || 0 }}</p>
                <p class="stat-change">待审核: {{ statistics.pendingTeachers || 0 }}</p>
              </div>
            </div>
          </div>

          <!-- 快速操作 -->
          <div class="quick-actions">
            <h3>快速操作</h3>
            <div class="action-buttons">
              <button class="action-btn" @click="navigateTo('/user-audit')">
                <i class="icon">✅</i>
                <span>审核用户</span>
              </button>
              <button class="action-btn" @click="navigateTo('/user-management')">
                <i class="icon">👤</i>
                <span>用户管理</span>
              </button>
              <div class="menu-item" @click="navigateTo('/team-management')">
                <i class="icon">⚡</i>
                <span>队伍管理</span>
              </div>
              <button class="action-btn" @click="navigateTo('/homepage-editor')">
                <i class="icon">✏️</i>
                <span>编辑主页</span>
              </button>
              <button class="action-btn" @click="navigateTo('/system-notifications')">
                <i class="icon">📢</i>
                <span>通知管理</span>
              </button>
              <button class="action-btn" @click="navigateTo('/news-management')">
                <i class="icon">📝</i>
                <span>发布新闻</span>
              </button>
              <button class="action-btn" @click="navigateTo('/event-management')">
                <i class="icon">🏆</i>
                <span>赛事管理</span>
              </button>
            </div>
          </div>

          <!-- 详细统计数据 -->
          <div class="data-table">
            <h3>（近7天）用户注册统计数据</h3>
            <div class="table-container">
              <table>
                <thead>
                  <tr>
                    <th>时间</th>
                    <th>新增学生</th>
                    <th>新增教师</th>
                    <th>总新增</th>
              
                  </tr>
                </thead>
                <tbody>
                  <tr v-if="detailLoading">
                    <td colspan="4" class="loading-data">加载中...</td>
                  </tr>
                  <tr v-else v-for="item in detailData" :key="item.date">
                    <td>{{ formatDate(item.date) }}</td>
                    <td>{{ item.newStudents || 0 }}</td>
                    <td>{{ item.newTeachers || 0 }}</td>
                    <td>{{ item.totalNew || 0 }}</td>
                  </tr>
                  <tr v-if="!detailLoading && detailData.length === 0">
                    <td colspan="4" class="no-data">暂无数据</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { useAdminStore } from '@/stores/admin.js'
import { getUserStatisticsService, getDailyUserStatisticsService } from '@/api/admin.js'

const router = useRouter()
const route = useRoute()
const tokenStore = useTokenStore()
const adminStore = useAdminStore()

// 当前路由
const currentRoute = computed(() => {
  return route.name?.toLowerCase() || 'dashboard'
})

// 管理员姓名
const adminName = computed(() => {
  return adminStore.getAdminName()
})

// 统计数据
const statistics = ref({
  totalStudents: 0,
  totalTeachers: 0,
  pendingStudents: 0,
  pendingTeachers: 0,
  totalNews: 0,
  totalNotifications: 0
})

// 详细统计数据
const detailData = ref([])
const detailLoading = ref(false)

// 格式化日期显示
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
}


// 导航到指定路由
const navigateTo = (path) => {
  router.push(path)
}

// 退出登录
const handleLogout = () => {
  tokenStore.removeToken()
  adminStore.clearAdminInfo()
  router.push('/login')
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const result = await getUserStatisticsService()
    if (result.code === 200) {
      statistics.value = result.data
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载详细统计数据
const loadDetailData = async () => {
  detailLoading.value = true
  try {
    console.log('开始加载详细统计数据...') // 调试信息
    const result = await getDailyUserStatisticsService(7) // 获取最近7天的数据
    console.log('详细统计数据API返回:', result) // 调试信息

    if (result.code === 200) {
      detailData.value = result.data || []
      console.log('详细统计数据:', detailData.value) // 调试信息
    } else {
      console.error('获取详细统计数据失败:', result.message)
      detailData.value = []
    }
  } catch (error) {
    console.error('加载详细统计数据失败:', error)
    detailData.value = []
  } finally {
    detailLoading.value = false
  }
}

// 页面初始化
onMounted(() => {
  if (!tokenStore.token) {
    router.push('/login')
    return
  }
  loadStatistics()
  loadDetailData()
})
</script>

<style scoped>
@import '@/assets/css/Dashboard.css';
</style>
